package com.example.springverify.Controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ICaptcha;
import cn.hutool.captcha.LineCaptcha;
import com.example.springverify.model.CaptchaProperties;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RequestMapping("/captcha")
@RestController
public class CaptchaController {
    private final long VALID_TIME = 60*1000;
    @Autowired
    private CaptchaProperties captchaProperties;
    @RequestMapping("/get")
    public void getCaptcha(HttpServletResponse response,HttpSession session){
        ICaptcha captcha = CaptchaUtil.createLineCaptcha(captchaProperties.getHeight(), captchaProperties.getWeight());
        try {
            captcha.write(response.getOutputStream());
            //拒绝前端缓存
            response.setHeader("Prama","No-cache");
            //设置图片生成模式
            response.setContentType("image/jpeg");
            //定义 Session
            session.setAttribute(captchaProperties.getSession().getCode(),captcha.getCode());
            session.setAttribute(captchaProperties.getSession().getDate(),System.currentTimeMillis());
            //关闭response 流
            response.getOutputStream().close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //验证,返回的是一个Boolean类型,所以不能使用Controller
    @RequestMapping("/check")
    public Boolean check(String inputCaptcha,HttpSession session){
        //参数校验
        if(!StringUtils.hasLength(inputCaptcha)){
            return false;
        }
        String result = (String) session.getAttribute(captchaProperties.getSession().getCode());
        Long date = (Long) session.getAttribute(captchaProperties.getSession().getDate());
        if(inputCaptcha.equalsIgnoreCase(result)&&date!=null&&(System.currentTimeMillis()-date)<VALID_TIME){
            return true;
        }
        return false;
    }
}
